package com.bigmi.article.service.serviceImpl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bigmi.article.mapper.ArticleContentMapper;
import com.bigmi.article.mapper.ArticleMapper;
import com.bigmi.article.service.ArticleFreemarkerService;
import com.bigmi.article.service.ArticleService;
import com.bigmi.file.service.FileStorageService;
import com.bigmi.model.article.pojo.ApArticle;
import com.bigmi.model.article.pojo.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;

@Slf4j
@Service
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private ArticleContentMapper articleContentMapper;

    //freemarker配置
    @Autowired
    private Configuration configuration;

    //minio文件上传服务
    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    ArticleMapper articleMapper;

    @Override
    public void buildtoMinio(ApArticle apArticle, String content) {
        //获取文章内容
        //根据文章id查询
        //获取文章内容
        if (StringUtils.isNotBlank(content)){
            //通过freemaker生成文件
            //输出字符流
            StringWriter writer = new StringWriter();
            Template template = null;
            try {
                template = configuration.getTemplate("article.ftl");
                HashMap<String, Object> map = new HashMap<>();
                //将json转换为对象
                JSONArray objects = JSONArray.parseArray(content);
                map.put("content", objects);
                template.process(map,writer);
            } catch (Exception e) {
                e.printStackTrace();
            }

            ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(writer.toString().getBytes());
            //把html文件上传到minio

            String path = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", arrayInputStream);
            //修改ap-article表，保存static—url字段
            //ApArticle apArticle = new ApArticle();

            //apArticle.setId(apArticle.getId());
            apArticle.setStaticUrl(path);
            articleService.updateById(apArticle);
        }
    }
}
